package encome.work.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import encome.work.dao.Menu;
import encome.work.dao.Permission;
import encome.work.dao.Role;
import encome.work.mapper.MenuMapper;
import encome.work.mapper.PermissionMapper;
import encome.work.mapper.RoleMapper;
import encome.work.service.RoleService;
import encome.work.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ajie
 * @createTime 2021年08月11日 20:42:00
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Result findPage(QueryInfo queryInfo) {
        Page<Role> rolePage = new Page<>(queryInfo.getPageNumber(), queryInfo.getPageSize());
        roleMapper.findPage(rolePage, queryInfo.getQueryString());
        List<Role> records = rolePage.getRecords();
        records.forEach(item -> {
            // 查询角色下菜单信息
            List<Menu> menus = menuMapper.findByRoleId(item.getId());
            menus.forEach(menu -> {
                List<Menu> children = menuMapper.findByRoleIdAndParentId(menu.getId(), item.getId());
                menu.setChildren(children);
            });
            item.setMenus(menus);
            // 查询该角色权限信息
            List<Permission> permissions = permissionMapper.findByRoleId(item.getId());
            item.setPermissions(permissions);
        });
        rolePage.setRecords(records);
        return Result.success("分页查询成功", records);
    }

    @Transactional
    @Override
    public Result insert(Role role) {
        log.info("查询角色信息是否存在");
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("label", role.getLabel());
        Role sysRole = roleMapper.selectOne(roleQueryWrapper);
        if (null != sysRole) {
            return Result.fail("该角色已经存在");
        }
        //插入角色信息
        roleMapper.insert(role);
        if (role.getPermissions().size() > 0) {
            log.info("再添加对应的权限数据");
            role.getPermissions().forEach(item -> roleMapper.insertPermissions(role.getId(), item.getId()));
        }
        if (role.getMenus().size() > 0) {
            role.getMenus().forEach(item -> roleMapper.insertMenus(role.getId(), item.getId()));
        }
        redisUtils.delKey("userInfo_" + SecurityUtils.getUsername());
        return Result.success("添加角色信息成功！");
    }

    @Override
    public Result delete(Long id) {
        log.info("查询该角色信息下是否有菜单权限");
        List<Menu> menus = menuMapper.findByRoleId(id);
        List<Menu> childrens = new ArrayList<>();
        menus.forEach(item -> {
            childrens.addAll(menuMapper.findByRoleIdAndParentId(item.getId(), id));
        });
        if (menus.size() > 0 || childrens.size() > 0) {
            return Result.fail("删除失败，该角色下拥有菜单信息，请先删除对应的菜单信息！");
        }
        if (permissionMapper.findByRoleId(id).size() > 0) {
            return Result.fail("删除失败，该角色下拥有权限信息，请先删除对应的权限信息！");
        }
        roleMapper.deleteById(id);
        redisUtils.delKey("userInfo_" + SecurityUtils.getUsername());
        return Result.success("删除成功！");
    }

    @Transactional
    @Override
    public Result update(Role role) {
        roleMapper.updateById(role);
        if (role.getPermissions().size() > 0) {
            log.info("先删除对应权限数据");
            roleMapper.deletePermissionById(role.getId());
            log.info("再添加对应的权限数据");
            role.getPermissions().forEach(item -> roleMapper.insertPermissions(role.getId(), item.getId()));
        }
        if (role.getMenus().size() > 0) {
            roleMapper.deleteMenuById(role.getId());
            role.getMenus().forEach(item -> roleMapper.insertMenus(role.getId(), item.getId()));
        }
        redisUtils.delKey("userInfo_" + SecurityUtils.getUsername());
        return Result.success("修改角色信息成功！");
    }

    @Override
    public Result findAll() {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("status", 1);
        List<Role> roles = roleMapper.selectList(roleQueryWrapper);
        return Result.success("查询所有角色成功", roles);
    }
}
